package com.ztjava.core.tool;

import java.math.BigDecimal;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.core.Constant;

public class FormTool {
	public static Ret getFormValue(Controller controller,String model,String code){

		Ret ret = new Ret();
		Cache cache = Redis.use();
		if(!cache.hexists(Constant.R_PRE+"COMMON_FORM", model)){
			ret.set(Constant.RESULT, Constant.ERROR);
			ret.set(Constant.MESSAGE, "不存在的表单配置！");
			return ret;
		}
		Map<String,Map<String,Record>> modelMap = cache.hget(Constant.R_PRE+"COMMON_FORM", model);
		Map<String,Record> map = modelMap.get(code);
		if(map==null){
			ret.set(Constant.RESULT, Constant.ERROR);
			ret.set(Constant.MESSAGE, "不存在的表单配置！");
			return ret;
		}
		String validator = null;
		String data_type = null;
		Integer max_length = null;
		Integer min_length = null;
		JSONObject result = new JSONObject();
		for(String key:map.keySet()){
			Record record = map.get(key);
			String value = controller.getPara(record.getStr("name"));
			validator = record.getStr("validator");
			if(validator!=null&&!validator.equals("")){
				//验证必填
				if(validator.indexOf("required")>-1){
					if(value==null||value.trim().equals("")){
						ret.set(Constant.RESULT, Constant.ERROR);
						ret.set(Constant.MESSAGE, record.getStr("name")+"不能为空！");
						return ret;
					}
				}
			}
			max_length = record.getInt("max_length");
			if(max_length!=null&&value.length()>max_length){
				ret.set(Constant.RESULT, Constant.ERROR);
				ret.set(Constant.MESSAGE, record.getStr("name")+"不能超过"+max_length+"个字符！");
				return ret;
			}
			min_length = record.getInt("min_length");
			if(min_length!=null&&value.length()<min_length){
				ret.set(Constant.RESULT, Constant.ERROR);
				ret.set(Constant.MESSAGE, record.getStr("name")+"不能少于"+min_length+"个字符！");
				return ret;
			}
			data_type = record.getStr("data_type");
			switch (data_type) {
				case "varchar":
					result.put(record.getStr("name"), value);
					break;
				case "timestamp":
					result.put(record.getStr("name"), value);
					break;
				case "int":
					result.put(record.getStr("name"), Integer.parseInt(value));
				case "decimal":
					result.put(record.getStr("name"), new BigDecimal(value));
				default:
					result.put(record.getStr("name"), value);
					break;
			}
		}
		ret.set(Constant.RESULT, Constant.SUCCESS);
		ret.set(Constant.MESSAGE, "操作成功！");
		ret.set("form_info", result.toJSONString());
		return ret;
	}
}
